﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// using Coravel.Mailer.Mail.Mailers;
// using Coravel.Mailer.Mail.Renderers;
using CRM.Extensions;
using CRM.Models;
using CRM.Models.Email;
using CRM.ViewModels.Email;
// using MailKit.Security;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace CRM.Controllers.Email
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailConfigController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<EmailConfigController> _logger;
        private readonly UserManager<User> _userManager;

        public EmailConfigController(MyDbContext dbContext, UserManager<User> userManager,
            ILogger<EmailConfigController> logger)
        {
            _dbContext = dbContext;
            _userManager = userManager;
            _logger = logger;
        }

        [HttpGet(nameof(Index))]
        public async Task<ResultStruct> Index()
        {
            var user = await _userManager.GetUserAsync(User);
            var result =
                await _dbContext.EmailConfig
                    .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                                m.UserId == user.Id)
                    .ToPaginateAsync();
            return Success(result);
        }

        [HttpGet(nameof(GetEmailAccountList))]
        public async Task<ResultStruct> GetEmailAccountList([FromQuery] int? groupId, [FromQuery] string emailAddress)
        {
            var user = await _userManager.GetUserAsync(User);
            var data = await _dbContext.EmailConfig
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                            m.UserId == user.Id)
                .WhenWhere(groupId != null, i => i.EmailConfigGroupId == groupId)
                .WhenWhere(!string.IsNullOrEmpty(emailAddress),
                    i => i.EmailAddress.StartsWith(emailAddress) || i.EmailAddress.EndsWith(emailAddress))
                .ToPaginateAsync(Request);
            return Success(data);
        }

        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(EmailConfigVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var model = vm.NewModel(user);
            await _dbContext.EmailConfig.AddAsync(model);
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        [HttpGet(nameof(Info))]
        public async Task<ResultStruct> Info(int id)
        {
            var user = await _userManager.GetUserAsync(User);
            return Success(await _dbContext.EmailConfig
                .Where(m => m.Id == id && m.OemId == user.OemId && m.CompanyId == user.CompanyId &&
                            m.GroupId == user.GroupId && m.UserId == user.Id)
                .FirstOrDefaultAsync());
        }

        [HttpPost(nameof(Edit))]
        public async Task<ResultStruct> Edit(EmailConfigVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            var row = await _dbContext.EmailConfig
                .Where(m => m.Id == vm.Id && m.OemId == user.OemId && m.CompanyId == user.CompanyId &&
                            m.GroupId == user.GroupId && m.UserId == user.Id)
                .FirstOrDefaultAsync();
            if (row is null)
            {
                return Error(message: "信息不存在");
            }

            row.Name = vm.Name;
            row.EmailAddress = vm.EmailAddress;
            row.Secret = vm.Secret;
            row.Host = vm.Host;
            row.Port = vm.Port.Value;
            row.Ssl = vm.Ssl;
            row.MaxLastDaySendNum = vm.MaxLastDaySendNum;
            await _dbContext.SaveChangesAsync();

            return Success(message: "更新成功");
        }
        
        [HttpPost("[action]/{id:int}")]
        public Task<ResultStruct> VerificationSuccess(int id)
        {
            return ChangeState(id, EmailVerification.Success);
        }
        
        [HttpPost("[action]/{id:int}")]
        public Task<ResultStruct> VerificationFailed(int id)
        {
            return ChangeState(id, EmailVerification.Failed);
        }
        
        private async Task<ResultStruct> ChangeState(int id, EmailVerification verification)
        {
            var user = await _userManager.GetUserAsync(User);
            var row = await _dbContext.EmailConfig
                .Where(m => m.Id == id && m.OemId == user.OemId && m.CompanyId == user.CompanyId &&
                            m.GroupId == user.GroupId && m.UserId == user.Id)
                .FirstOrDefaultAsync();
            if (row is null)
            {
                return Error(message: "信息不存在");
            }
            row.State = verification;
            await _dbContext.SaveChangesAsync();

            return Success(message: "更新成功");
        }

        [HttpPost("[action]/{id:int}")]
        [HttpDelete("[action]/{id:int}")]
        public async Task<ResultStruct> Delete(int id)
        {
            var user = await _userManager.GetUserAsync(User);

            var result = await _dbContext.EmailConfig
                .Where(m => m.Id == id && m.OemId == user.OemId && m.CompanyId == user.CompanyId &&
                            m.GroupId == user.GroupId && m.UserId == user.Id)
                .FirstOrDefaultAsync();

            if (result is not null)
            {
                _dbContext.Remove(result);
                await _dbContext.SaveChangesAsync();
            }

            return Success("删除成功");
        }

        /// <summary>
        ///  添加发件人
        /// </summary>
        /// <param name="emailConfigVm"></param>
        /// <returns></returns>
        [HttpPost(nameof(ConfigAddressee))]
        public async Task<ResultStruct> ConfigAddressee([FromBody] EmailConfigVM emailConfigVm)
        {
            var user = await _userManager.GetUserAsync(User);
            var duplicate = await _dbContext.EmailConfig.Where(e => e.EmailType == emailConfigVm.EmailType && e.EmailAddress == emailConfigVm.EmailAddress && e.UserId == user.Id).FirstOrDefaultAsync();
            if (duplicate is not null)
            {
                return Error(message: $"邮箱[{emailConfigVm.EmailAddress}]已添加");
            }
            var emailConfig = emailConfigVm.NewModel(user);

            await _dbContext.EmailConfig.AddAsync(emailConfig);
            await _dbContext.SaveChangesAsync();
            return Success("邮箱添加成功");
        }

        /// <summary>
        /// 批量添加发件人
        /// </summary>
        /// <param name="emailConfigVm"></param>
        /// <returns></returns>
        [HttpPost(nameof(BatchConfigAddressee))]
        public async Task<ResultStruct> BatchConfigAddressee(List<EmailConfigVM> emailConfigVm)
        {
            var user = await _userManager.GetUserAsync(User);
            var inputEmailList = emailConfigVm.Select(e => e.EmailAddress);
            var existsEmailList = await _dbContext.EmailConfig.Where(m =>
                    m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                    m.UserId == user.Id)
                .Where(e => inputEmailList.Contains(e.EmailAddress))
                .Select(e => e.EmailAddress)
                .ToListAsync();

            var emailConfig = emailConfigVm.Where(e => !existsEmailList.Contains(e.EmailAddress))
                .Select(e => e.NewModel(user)).ToList();

            if (emailConfig.Count == 0)
                return Success(message: "无新增邮箱账号");

            // try
            // {
            //     // await smtpMailer.Au(new NewUserViewMailable());
            // }
            // catch (AuthenticationException)
            // {
            //     return Error(message: "账号密码错误");
            // }
            // catch (Exception e)
            // {
            //     _logger.LogError(e.Message);
            //     return Error(message: "未知错误");
            // }

            await _dbContext.EmailConfig.AddRangeAsync(emailConfig);
            await _dbContext.SaveChangesAsync();
            return Success("邮箱添加成功");
        }

        public record ChangeGroupRecord(List<int> Id, int GroupId);

        [HttpPost(nameof(ChangeGroup))]
        public async Task<ResultStruct> ChangeGroup(ChangeGroupRecord Request)
        {
            var id = Request.Id;
            var groupId = Request.GroupId;
            if (groupId <= 0)
            {
                return Error(new object(), "参数错误");
            }

            var user = await _userManager.GetUserAsync(User);

            await _dbContext.EmailConfig
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.UserId == user.Id)
                .Where(m => id.Contains(m.Id))
                .ForEachAsync(m => m.EmailConfigGroupId = groupId);

            var result = await _dbContext.SaveChangesAsync();

            if (result > 0)
            {
                return Success(new object(), "更新成功");
            }

            return Error(new object(), "更新失败");
        }
    }
}